package com.cbgolf.oa.manager;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import butterknife.ButterKnife;
import com.cbgolf.oa.R;
import com.cbgolf.oa.adapter.MyBaseAdapter;
import com.cbgolf.oa.adapter.recycle.CommonAdapter;
import com.cbgolf.oa.adapter.recycle.ViewHolder;
import com.cbgolf.oa.entity.CaddieBean;
import com.cbgolf.oa.entity.CustomBean;
import com.cbgolf.oa.entity.ListBean;
import com.cbgolf.oa.entity.ParkBean;
import com.cbgolf.oa.entity.StatisticsInfo;
import com.cbgolf.oa.entity.StatisticsInfo.Customer;
import com.cbgolf.oa.util.ScreenUtil;
import com.cbgolf.oa.util.TextUtil;
import com.cbgolf.oa.util.TypeUtil;
import com.cbgolf.oa.util.Util;
import com.cbgolf.oa.util.ViewUtils;
import com.cbgolf.oa.widget.ListViewNew;
import com.cbgolf.oa.widget.autolayout.utils.AutoUtil;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lq
 * @date 2018/5/3
 */

public class PopManager {

  PopManager() {

  }

  public static PopManager getInstance() {
    return Inner.manager;
  }

  private static class Inner {

    public static PopManager manager = new PopManager();
  }


  private int width;
  private int height;
  private int mType;
  private int itemLayout;
  private int backgroundColor;
  private View asView;
  private ParkBean parkBean;
  private IPopManagerListWaiter listWorker;
  private List<ListBean> listData;
  private String phone;

  public PopManager setWidth(int width) {
    this.width = width;
    return this;
  }

  public PopManager setHeight(int height) {
    this.height = height;
    return this;
  }

  public PopManager setItemlayout(int itemLayout) {
    this.itemLayout = itemLayout;
    return this;
  }

  public PopManager setBackgroundColor(int color) {
    this.backgroundColor = color;
    return this;
  }

  public PopManager setAsView(View asView) {
    this.asView = asView;
    return this;
  }

  public PopManager setListWorker(IPopManagerListWaiter worker) {
    this.listWorker = worker;
    return this;
  }

  public PopManager setListData(List<ListBean> list) {
    this.listData = list;
    return this;
  }

  public PopManager setType(int type) {
    this.mType = type;
    return this;
  }

  public PopManager setParkBean(ParkBean bean) {
    this.parkBean = bean;
    return this;
  }


  public PopManager showParkMapCaddiePlayerWorker(Activity context) {
    if (null == parkBean) {
      return this;
    }
    if (null != pop && pop.isShowing()) {
      pop.dismiss();
      pop = null;
      return this;
    }
    if (mType == DataManager.PLAYER) {
      return this;
    }
    if (mType == DataManager.STATISTICS_CAR_USING) {
      showCarUsingPop(context);
      return this;
    }
    pop = new PopupWindow(context);
    View view = ViewUtils.inflate(context, R.layout.pop_map_caddie_worker);
    View layout = ButterKnife.findById(view, R.id.layout);
    ImageView iconIv = ButterKnife.findById(view, R.id.iv_pop_map_caddie_icon);
    ImageView telIv = ButterKnife.findById(view, R.id.iv_pop_map_caddie_tel);
    TextView nameTv = ButterKnife.findById(view, R.id.tv_pop_map_caddie_name);
    TextView levelTv = ButterKnife.findById(view, R.id.tv_pop_map_caddie_level);
    TextView csNumTv = ButterKnife.findById(view, R.id.tv_pop_map_caddie_player_num);
    View playerView = ButterKnife.findById(view, R.id.ll_pop_map_caddie_player_layout);
    ListViewNew listView = ButterKnife.findById(view, R.id.lv_pop_map_caddie_player);
    ViewUtils.setVisible(playerView, mType == DataManager.STATISTICS_CADDIE_IN_PARK
        || mType == DataManager.STATISTICS_CAR_USING
        || mType == DataManager.CADDIE);
    phone = null;
    switch (mType) {
      case DataManager.WORKER:
        ViewUtils.setImage(iconIv, R.mipmap.head_icon_xinjiang);
        ViewUtils.setText(levelTv, "工作人员");
        ViewUtils.setText(nameTv, (null != parkBean.statisticsInfo) ?
            parkBean.statisticsInfo.userName : "");
        phone = null != parkBean.statisticsInfo ? parkBean.statisticsInfo.phone : "";
        try {
          ViewUtils.setText(csNumTv, parkBean.statisticsInfo.departmentName);
        } catch (Exception e) {

        }

        break;
      case DataManager.CADDIE:
      case DataManager.STATISTICS_CADDIE_IN_PARK:
        try {
          ViewUtils.setImage(iconIv, R.mipmap.head_icon_xinjiang);
          ViewUtils.setText(levelTv, (null != parkBean.statisticsInfo
              && !Util.isNull(parkBean.statisticsInfo.levelName)) ?
              parkBean.statisticsInfo.levelName + "级球僮"
              : "球僮");
          ViewUtils.setText(nameTv, (null != parkBean.statisticsInfo) ?
              mType == DataManager.CADDIE ? parkBean.statisticsInfo.userName
                  : parkBean.statisticsInfo.caddieName
              : "");
          phone = null != parkBean.statisticsInfo ? parkBean.statisticsInfo.phone : "";
          if (null != parkBean.statisticsInfo &&
              null != parkBean.statisticsInfo
              && !Util.listIsNull(parkBean.statisticsInfo.customerInfo)) {
            ViewUtils
                .setText(csNumTv,
                    getCaddiePlayerType(TypeUtil.getInt(parkBean.statisticsInfo.customerCount)));
          } else {
            ViewUtils.setText(csNumTv, "");
            ViewUtils.setVisible(playerView, false);
          }
          setPlayerAdapter(context, listView, parkBean.statisticsInfo);
        } catch (Exception e) {

        }
        break;
      case DataManager.STATISTICS_CAR_USING:
        break;
      default:
        break;
    }
    ViewUtils.setClick(telIv, v -> Util.callPhone(context, phone));
    pop = new PopupWindow(context);
    pop.setContentView(view);
    setPop(pop);
    showPopBottom(context, pop);
    pop.setOnDismissListener(() -> {
      realse();
    });
    return this;
  }

  private PopManager showCarUsingPop(Context context) {
    if (null == parkBean) {
      return this;
    }
    if (null != pop && pop.isShowing()) {
      pop.dismiss();
      pop = null;
      return this;
    }
    View view = ViewUtils.inflate(context, R.layout.include_recyclerview_roundbg);
    View layout = ButterKnife.findById(view, R.id.layout);
    RecyclerView recyclerView = ButterKnife.findById(view, R.id.recycleView);
    setCarUsingFirstAdapter(context, recyclerView);
    pop = new PopupWindow(context);
    pop.setContentView(view);
    setPop(pop);
    showPopBottom((Activity) context, pop);
    pop.setOnDismissListener(() -> {
      realse();
    });
    return this;
  }

  private void setCarUsingFirstAdapter(Context context, RecyclerView recyclerView) {
    if (null == parkBean || null == parkBean.statisticsInfo || Util
        .listIsNull(parkBean.statisticsInfo.caddieInfo)) {
      return;
    }
    CommonAdapter<CaddieBean> adapter = new CommonAdapter<CaddieBean>(context,
        R.layout.item_carusing_pop_first,
        parkBean.statisticsInfo.caddieInfo) {
      @Override
      protected void convert(ViewHolder holder, CaddieBean bean, int position) {
        if (null == bean) {
          return;
        }
        holder.setImageResource(R.id.iv_pop_map_caddie_icon, R.mipmap.head_icon_xinjiang)
            .setText(R.id.tv_pop_map_caddie_name, TextUtil.Text(bean.userName))
            .setText(R.id.tv_pop_map_caddie_level, !Util.isNull(bean.levelName) ?
                bean.levelName + "级球僮"
                : "球僮")
            .setOnClickListener(R.id.iv_pop_map_caddie_tel,
                v -> Util.callPhone((Activity) context, bean.phone))
            .setText(R.id.tv_pop_map_caddie_player_num, !Util.listIsNull(bean.customerInfo) ?
                getCaddiePlayerType(bean.customerInfo.size()) : "");
        setCarPlayerAdapter(context, holder.getView(R.id.lv_pop_map_caddie_player),
            bean.customerInfo);
      }
    };
    LinearLayoutManager lm = new LinearLayoutManager(context);
    lm.setOrientation(LinearLayoutManager.VERTICAL);
    recyclerView.setLayoutManager(lm);
    recyclerView.setHasFixedSize(true);
    recyclerView.setAdapter(adapter);
  }

  private String getCaddiePlayerType(int size) {
    String res = "";
    switch (size) {
      case 1:
        res = "单包";
        break;
      case 2:
        res = "双包";
        break;
      case 3:
        res = "一托三";
        break;
      case 4:
        res = "一托四";
        break;
      default:
        break;
    }
    return res;
  }

  private void setPlayerAdapter(Context context, ListViewNew listView,
      StatisticsInfo info) {
    List<StatisticsInfo.Customer> list = null;
    if (null == listView) {
      return;
    }
    if (null != info) {
      list = info.customerInfo;
    }
    if (null == list) {
      list = new ArrayList<>();
    }
    if (list.size() < 4) {
      for (int i = list.size(); i < 4; i++) {
        list.add(new StatisticsInfo().getCustomer());
      }
    }

    MyBaseAdapter<StatisticsInfo.Customer> adapter = new MyBaseAdapter<Customer>(
        R.layout.item_player_info,
        context,
        list) {
      @Override
      public View getView(int position, View convertView, ViewGroup parent,
          StatisticsInfo.Customer bean) {
        if (null == bean) {
          return convertView;
        }
        setText(R.id.tv_player, bean.name);
        setText(R.id.tv_holenum, bean.hole);
        setText(R.id.tv_cardnum, bean.customerCardNumber);
        setText(R.id.tv_car, bean.courseCar);
        setBackgroundColor(R.id.layout,
            ContextCompat.getColor(context, position % 2 == 0 ? R.color.bg : R.color.divider_2));
        return convertView;
      }
    };
    listView.setAdapter(adapter);
  }

  private void setCarPlayerAdapter(Context context, ListViewNew listView,
      List<CustomBean> list) {
    if (null == listView || Util.listIsNull(list)) {
      return;
    }
//    if (list.size() < 4) {
//      CustomBean bean;
//      for (int i = list.size(); i < 4; i++) {
//        list.add(new CustomBean());
//      }
//    }
    MyBaseAdapter<CustomBean> adapter = new MyBaseAdapter<CustomBean>(
        R.layout.item_player_info,
        context,
        list) {
      @Override
      public View getView(int position, View convertView, ViewGroup parent,
          CustomBean bean) {
        if (null == bean) {
          return convertView;
        }
        setText(R.id.tv_player, bean.name);
        setText(R.id.tv_holenum, bean.hole);
        setText(R.id.tv_cardnum, bean.customerCardNumber);
        setText(R.id.tv_car, bean.courseCar);
        setBackgroundColor(R.id.layout,
            ContextCompat.getColor(context, position % 2 == 0 ? R.color.bg : R.color.divider_2));
        return convertView;
      }
    };
    listView.setAdapter(adapter);
  }

  public void showList(Activity context) {
    if (Util.listIsNull(listData)) {
      return;
    }
    if (null != pop && pop.isShowing()) {
      pop.dismiss();
      pop = null;
      return;
    }
    View view = ViewUtils.inflate(context, R.layout.include_recycleview);
    ViewUtils.setVisible(ButterKnife.findById(view, R.id.topline), false);
    RecyclerView recyclerView = ButterKnife.findById(view, R.id.recycleView);
    setRecyviewAdapter(context, recyclerView);
    pop = new PopupWindow(context);
    pop.setContentView(view);
    setPop(pop);
    if (null != asView) {
      pop.showAsDropDown(asView);
    }
    pop.setOnDismissListener(() -> ScreenUtil.LightOn(context));
    ScreenUtil.LightOff(context);

  }

  private PopupWindow pop;

  private void setRecyviewAdapter(Context context, RecyclerView recyclerView) {
    if (null == recyclerView || Util.listIsNull(listData)) {
      return;
    }
    CommonAdapter<ListBean> adapter = new CommonAdapter<ListBean>(context, itemLayout, listData) {
      @Override
      protected void convert(ViewHolder holder, ListBean bean, int position) {
        if (null == bean) {
          return;
        }
        holder.setText(R.id.tv, TextUtil.Text(bean.nameForShow))
            .setOnClickListener(R.id.layout, v -> {
              if (null != pop) {
                pop.dismiss();
              }
              if (null != listWorker) {
                listWorker.choice(bean.idForName, bean.nameForShow, position);
              }
            });

      }
    };
    LinearLayoutManager lm = new LinearLayoutManager(context);
    lm.setOrientation(LinearLayoutManager.VERTICAL);
    recyclerView.setLayoutManager(lm);
    recyclerView.setAdapter(adapter);
  }

//    public void showTimePop(Context context,int type) {
//      if (null != pop && pop.isShowing()) {
//        pop.dismiss();
//        pop = null;
//        return;
//      }
//      pop = new PopupWindow(context);
//      View view = LayoutInflater.from(context).inflate(R.layout.pop_time, null);
//      View layout = ButterKnife.findById(view, R.id.layout);
//      TextView sureTv = ButterKnife.findById(view, R.id.sureTv);
//      if (type == TIME) {
//        ViewUtils.setText(ButterKnife.findById(view, R.id.title_tv), "选择TEETIME");
//      }
//      dateCv = ButterKnife.findById(view, R.id.dateCv);
//      teetimeCv = ButterKnife.findById(view, R.id.teetimeCv);
//      ViewUtils.setVisible(dateCv, (type == DATE));
//      ViewUtils.setVisible(teetimeCv, (type == TIME));
//      ViewUtils.setLayoutParams(layout, ScreenUtil.getWidth(), -2);
//      pop.setContentView(view);
//      pop.setWidth(ScreenUtil.getWidth());
//      pop.setHeight(ScreenUtil.getHeight() * 2 / 5);
//      pop.setTouchable(true);
//      pop.setOutsideTouchable(true);
//      pop.setBackgroundDrawable(new ColorDrawable(0xffffffff));
//      pop.setFocusable(true);
//      sureTv.setOnClickListener(v -> {
//        if (type == DATE) {
//          timeTv.setText(dateLable);
//          teetimeSelect = -1;
//          teetimeId = null;
//          teetimeLable = null;
//          teetimeTv.setText("");
//          worker.getTeetime(TypeUtil.parseLong(DateUtil.dateToStamp(dateLable, DateUtil.formatYMD)));
////                worker.getTeetime(mapDate.get(position));
////        worker.getPrice(TypeUtil.parseLong(DateUtil.dateToStamp(dateLable, DateUtil.formatYMD)));
////                worker.getPrice(mapDate.get(position));
//          selectTime = TypeUtil.parseLong(DateUtil.dateToStamp(dateLable, DateUtil.formatYMD));
//          worker.getPrice(selectTime, personNum);
//        } else {
//          teetimeId = DataUtil.getMapString(mapTeetime, teetimeSelect);
//          teetimeTv.setText(getTeetimeLable(teetimeLable));
//        }
//        pop.dismiss();
//      });
//      if (DATE == type) {
//        initWheel(dateCv, listDate, dateSelect, DATE);
//      } else {
//        initWheel(teetimeCv, listTeetime, 0, TIME);
//      }
//      try {
//        dateCv.setOnWheelItemSelectedListener((position, label) -> {
//          if (mapDate.containsKey(position)) {
//            dateSelect = position;
//            dateLable = DateUtil.stampToDate(mapDate.get(position) + "", DateUtil.formatYMD);
//          }
//        });
//        teetimeCv.setOnWheelItemSelectedListener((position, label) -> {
//          teetimeLable = label;
//          teetimeSelect = position;
//        });
//      } catch (Exception e) {
//        Log.e("catch--pop---------", e.toString() + "----");
//      }
//      pop.setOnDismissListener(() -> resetData());
//      pop.showAtLocation(ButterKnife.findById(context, R.id.root),
//          Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
//
//    }
//  }

  public void showTeetimeABPop(Context context,List<String> listCode,
      String codeType,View asView,IPopManagerListWaiter worker) {
    if (null != pop && pop.isShowing()) {
      pop.dismiss();
      pop = null;
      return;
    }
    if(Util.listIsNull(listCode)) {return;}
    pop = new PopupWindow(context);
    View view =ViewUtils.inflate(context,R.layout.pop_codetype);
    ListViewNew listView = ButterKnife.findById(view, R.id.listView);
    List<String> list = new ArrayList<>();
    for (int i = 0; i < listCode.size(); i++) {
      if (!Util.isEquals(listCode.get(i), codeType)) {
        list.add(listCode.get(i));
      }
    }
    MyBaseAdapter<String> adapter = new MyBaseAdapter<String>(R.layout.pop_codetype,
        context, list) {
      @Override
      public View getView(int position, View view, ViewGroup parent, String code) {
        if (Util.isNull(code)) {
          return view;
        }
        setVisible(R.id.listView, false);
        setVisible(R.id.tv, true);
        setText(R.id.tv, "Teetime-" + code.substring(0, 1) + "半场");
        view.findViewById(R.id.tv).setOnClickListener(v -> {
          pop.dismiss();
          if(null != worker) {
            worker.choice(code,"Teetime-" + code.substring(0, 1) + "半场",0);
          }
        });
        return view;
      }
    };
    listView.setAdapter(adapter);
    ViewUtils.setLlLayoutParams(listView,ScreenUtil.getWidth(), LayoutParams.WRAP_CONTENT);
    AutoUtil.auto(view);
    pop.setContentView(view);
    pop.setWidth(ScreenUtil.getWidth());
    pop.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
    pop.setOutsideTouchable(true);
    pop.setTouchable(true);
    pop.setFocusable(true);
    pop.setBackgroundDrawable(new ColorDrawable(0x00000000));
    pop.showAsDropDown(asView);


  }
  private void showPopBottom(Activity context, PopupWindow pop) {
    pop.setOnDismissListener(() -> ScreenUtil.LightOn(context));
    ScreenUtil.LightOff(context);
    pop.showAtLocation(ButterKnife.findById(context, R.id.root),
        Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    pop.setAnimationStyle(R.style.pop_bottom_enter);
  }

  private void setPop(PopupWindow pop) {
    pop.setWidth(width);
    pop.setHeight(height);
    pop.setOutsideTouchable(true);
    pop.setFocusable(true);
    pop.setTouchable(true);
    pop.setBackgroundDrawable(new ColorDrawable(0x00000000));
  }

  public void realse() {
    pop = null;
    asView = null;
    parkBean = null;
    listWorker = null;
    listData = null;
  }

  public interface IPopManagerListWaiter {

    void choice(String id, String name, int position);
  }



}
